"""The base Controller API

Provides the BaseController class for subclassing.
"""
from pylons import request, response, session, tmpl_context as c
from pylons.controllers import WSGIController
from pylons.controllers.util import redirect, redirect_to, abort
from pylons.templating import render_mako as render
from webhelpers.html import secure_form
from enlargeweb.model import meta
from enlargeweb.model.user import User
from routes import url_for
import helpers
import logging
log = logging.getLogger(__name__)

class BaseController(WSGIController):
	def __before__(self):
		if hasattr(self, 'requires_auth') and self.requires_auth:
			#auth check required
			if request.environ.get('repoze.who.identity') == None:
				#no user
				log.error('User is not logged in')
				abort(401)
			else:
				user = helpers.get_current_user()
				rights = str(self.requires_auth)
				log.debug('Page require rights: %s' % rights)
				provided = user.get_attr('rights')
				 
				if not provided:
					log.error('User %s has no rights.' % str(user) )
					abort(402)
					
				if provided.value == 'admin':
					log.info('Admin user by pass')
					return True
				
				if provided.value == 'user' and provided.value != rights:
					log.error('User %s has rights: %s, but %s required.' % ( str(user),
																			 provided.value,
																		 	 rights) )
					abort(402)
		else:
			log.debug('Page require NO rights.')
	
	def __call__(self, environ, start_response):
		try:
			return WSGIController.__call__(self, environ, start_response)
		finally:
			meta.Session.remove()

	def get_user_name(self):
		if 'user' not in session:
			return 'Anonymous'
		else:
			return '%s %s' % ( session['user_first_name'], session['user_second_name'])



